//
//  DiscoveryWebViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/9/2.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "DiscoveryWebViewController.h"
#import "DisconveryActicleBottomer.h"
#import "XXTGShareView.h"



@interface DiscoveryWebViewController ()

@property (nonatomic, strong) DisconveryActicleBottomer *bottomer;
@property (nonatomic, strong) XXTGShareView *shareView;

//分享相关字段
@property (copy, nonatomic) NSString * shareTitle;
@property (copy, nonatomic) NSString * shareDescription;
@property (copy, nonatomic) NSString * shareImage;
@property (strong, nonatomic) UIImage * shareUsedImage;
@property (copy, nonatomic) NSString * shareUrl;

@end

@implementation DiscoveryWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    {
        [self.baseNavView.rightNavBtn setImage:[UIImage imageNamed:@"share_icon_gray"] forState:UIControlStateNormal];
        self.baseNavView.rightNavBtn.hidden = NO;
        self.baseNavView.rightNavBtn.isNeedAnimation = YES;
        
        @weakify(self);
        self.baseNavView.rightNavBtn.tapBlock = ^{
            @strongify(self);
            
            [self shareToWechatSocialWithTitle:@"" description:@"" image:@"" url:@""];
        };

    }

    {
        [self.view addSubview:self.bottomer];
    }
    [self setupLayout];
}


- (void)setupLayout{
    
    _bottomer.mj_y = KScreenHeight - _bottomer.height;
    
}


#pragma mark - lifecycle methods

//MARK: - 分享
//分享选择平台
//分享图片到某个平台  微信/朋友圈 type 1/2
- (void)wxShareToSocialWithGetAwardTitle:(NSString *)title description:(NSString *)description image:(UIImage *)image url:(NSString *)url
{
    [[UIApplication sharedApplication].keyWindow addSubview:self.shareView];
    [self.shareView showShare];
    kWeakSelf(self)
    self.shareView.clickShareWechatButtonBlock = ^{
        //分享微信好友
        [weakself wxShareToSocialWithType:1 title:title description:description image:image url:url];
    };
    self.shareView.clickShareWechatFriendCircleButtonBlock = ^{
        //分享微信朋友圈
        [weakself wxShareToSocialWithType:2 title:title description:description image:image url:url];
    };
}

- (void)wxShareToSocialWithType:(NSInteger)type title:(NSString *)title description:(NSString *)description image:(UIImage *)image url:(NSString *)url
{
    if ([WXApi isWXAppInstalled] == YES) {
        //如果已经安装了微信app
        WXMediaMessage * message = [WXMediaMessage message];
        message.title = title;
        //        message.description = @"休息的时间还给你，买单享优惠";
        message.description = description;
        
        if (image) {
            // 缩略图 小于32KB
            UIImage * lastImage = [self compressImage:image toByte:31.8*1024];
            [message setThumbImage:lastImage];
        }
        
        WXImageObject *ext = [WXImageObject object];
        //图片
        NSData *imageData = UIImagePNGRepresentation(image);
        ext.imageData = imageData;
        message.mediaObject = ext;
        
        if (url && [url hasPrefix:@"http"]) {
            WXWebpageObject * webPageObject = [WXWebpageObject object];
            webPageObject.webpageUrl = url;
            message.mediaObject = webPageObject;
        }
        
        SendMessageToWXReq * req1 = [[SendMessageToWXReq alloc]init];
        req1.bText = NO;
        req1.message = message;
        //设置分享到朋友圈(WXSceneTimeline)、好友回话(WXSceneSession)、收藏(WXSceneFavorite)
        if (type == 1) {
            req1.scene = WXSceneSession;
        }else if (type == 2){
            req1.scene = WXSceneTimeline;
        }
        
        [WXApi sendReq:req1];
    }else {
        [self showHudWithMsg:@"您还没有安装微信"];
    }
}


//分享title，desc，imageURL，url到  微信/朋友圈
- (void)shareToWechatSocialWithTitle:(NSString *)title description:(NSString *)description image:(NSString *)image url:(NSString *)url
{
    kWeakSelf(self)
//    dispatch_sync(dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication].keyWindow addSubview:weakself.shareView];
        [self.shareView showShare];
//    });
    _shareTitle = title;
    _shareDescription = description;
    _shareImage = image;
    _shareUrl = url;
    self.shareView.clickShareWechatButtonBlock = ^{
        //分享微信好友
        [weakself shareToSocialWithType:1];
    };
    self.shareView.clickShareWechatFriendCircleButtonBlock = ^{
        //分享微信朋友圈
        [weakself shareToSocialWithType:2];
    };
}

- (void)shareToSocialWithType:(NSInteger)type
{
    if (_shareView) {
        [_shareView removeFromSuperview];
        _shareView = nil;
    }
    if ([WXApi isWXAppInstalled] == YES) {
        WXMediaMessage * message = [WXMediaMessage message];
        if (_shareTitle) {
            message.title = _shareTitle;
        }else {
            message.title = @"";
        }
        
        if (_shareDescription) {
            message.description = _shareDescription;
        }else {
            message.description = @"";
        }
        
        if (_shareImage) {
            
            NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:_shareImage]];
            UIImage * shareImage = [UIImage imageWithData:imageData];
            
            // 缩略图 小于32KB
            UIImage * lastImage = [self compressImage:shareImage toByte:31.8*1024];
            [message setThumbImage:lastImage];
            WXImageObject *ext = [WXImageObject object];
            //图片
            NSData *imageData1 = UIImagePNGRepresentation(shareImage);
            ext.imageData = imageData1;
            message.mediaObject = ext;
        }
        
        if (_shareUrl) {
            WXWebpageObject * webPageObject = [WXWebpageObject object];
            webPageObject.webpageUrl = _shareUrl;
            message.mediaObject = webPageObject;
        }
        
        SendMessageToWXReq * req1 = [[SendMessageToWXReq alloc]init];
        req1.bText = NO;
        req1.message = message;
        //设置分享到朋友圈(WXSceneTimeline)、好友回话(WXSceneSession)、收藏(WXSceneFavorite)
        if (type == 1) {
            req1.scene = WXSceneSession;
        }else if (type == 2){
            req1.scene = WXSceneTimeline;
        }
        
        [WXApi sendReq:req1];
    }else {
        [self showHudWithMsg:@"您还没有安装微信"];
    }
}

//压缩图片到指定尺寸
- (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
    // Compress by quality
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return image;
    
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
    UIImage *resultImage = [UIImage imageWithData:data];
    if (data.length < maxLength) return resultImage;
    
    // Compress by size
    NSUInteger lastDataLength = 0;
    while (data.length > maxLength && data.length != lastDataLength) {
        lastDataLength = data.length;
        CGFloat ratio = (CGFloat)maxLength / data.length;
        CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),
                                 (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
        UIGraphicsBeginImageContext(size);
        [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
        resultImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        data = UIImageJPEGRepresentation(resultImage, compression);
    }
    
    return resultImage;
}


#pragma mark - setter methods
#pragma mark - getter methods

- (DisconveryActicleBottomer *)bottomer{
    
    if (!_bottomer) {
        _bottomer = [[DisconveryActicleBottomer alloc] init];
    }
    return _bottomer;
}

- (XXTGShareView *)shareView
{
    if (!_shareView) {
        _shareView = [[XXTGShareView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
        
        @weakify(self);
        _shareView.dealShareBlock = ^(NSInteger params) {
            @strongify(self);
            
            switch (params) {
                case 0:
                {
                    [self showHudWithMsg:@"微信"];
                }
                    break;
                    
                case 1:
                {
                    [self showHudWithMsg:@"朋友圈"];

                }
                    break;
                    
                case 2:
                {
                    [self showHudWithMsg:@"微博"];

                }
                    break;
                    
                case 3:
                {
                    [self showHudWithMsg:@"QQ"];
                }
                    break;
                
                case 4:
                {
                    [self showHudWithMsg:@"站内豚友"];

                }
                    break;
                    
                case 5:
                {
                    [self showHudWithMsg:@"QQ空间"];

                }
                    break;
                
                default:
                {
                    [self showHudWithMsg:@"复制链接"];

                }
                    break;
            }
        };
        
    }
    return _shareView;
}


@end
